package com.fxz.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fxz.common.dto.PassDto;
import com.fxz.common.lang.Const;
import com.fxz.common.lang.Result;
import com.fxz.entity.SysRole;
import com.fxz.entity.SysUser;
import com.fxz.entity.SysUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author fxz
 * @since 2021-05-04
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {

    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    /**
     * 查询用户信息 以及该用户的角色
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result info(@PathVariable("id") Long id) {
        //用户信息
        SysUser user = sysUserService.getById(id);
        if (ObjectUtils.isEmpty(user)) {
            throw new IllegalArgumentException("没有该用户!");
        }
        //用户的角色信息
        List<SysRole> roles = sysRoleService.list(
                new LambdaQueryWrapper<SysRole>()
                        .inSql(SysRole::getId, "select role_id from sys_user_role where user_id = " + id)
        );
        user.setSysRoles(roles);
        return Result.succ(user);
    }

    /**
     * 模糊查询用户信息以及角色
     *
     * @param username 用户名
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result list(String username) {
        Page<SysUser> pageData = sysUserService.page(getPage(), new LambdaQueryWrapper<SysUser>().like(!StringUtils.isBlank(username), SysUser::getUsername, username));
        pageData.getRecords().forEach(item -> {
            List<SysRole> roles = sysRoleService.list(
                    new LambdaQueryWrapper<SysRole>()
                            .inSql(SysRole::getId, "select role_id from sys_user_role where user_id = " + item.getId())
            );
            item.setSysRoles(roles);
        });
        return Result.succ(pageData);
    }

    /**
     * 保存用户信息
     *
     * @param user 用户信息
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:user:save')")
    public Result save(@Validated @RequestBody SysUser user) {
        user.setCreated(LocalDateTime.now());
        user.setStatu(Const.STATUS_ON);
        //默认密码
        user.setPassword(passwordEncoder.encode(Const.DEFULT_PASSWORD));
        //默认头像
        user.setAvatar(Const.DEFULT_AVATAR);
        return Result.succ(sysUserService.save(user));
    }

    /**
     * 更新用户信息
     *
     * @param sysUser 用户信息
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public Result update(@Validated @RequestBody SysUser sysUser) {
        sysUser.setUpdated(LocalDateTime.now());
        sysUserService.updateById(sysUser);
        return Result.succ(sysUser);
    }

    /**
     * 批量删除用户
     *
     * @param ids 用户id
     */
    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result delete(@RequestBody Long[] ids) {
        sysUserService.removeByIds(Arrays.asList(ids));
        //删除中间表
        sysUserRoleService.remove(
                new LambdaQueryWrapper<SysUserRole>()
                        .in(SysUserRole::getUserId, ids)
        );
        return Result.succ("");
    }

    /**
     * 为用户分配角色
     *
     * @param userId  用户Id
     * @param roleIds 角色id
     */
    @Transactional
    @PostMapping("/role/{userId}")
    @PreAuthorize("hasAuthority('sys:user:role')")
    public Result rolePerm(@PathVariable("userId") Long userId, @RequestBody Long[] roleIds) {
        List<SysUserRole> list = new LinkedList<>();
        Arrays.stream(roleIds).forEach(r -> {
            SysUserRole userRole = new SysUserRole();
            userRole.setRoleId(r);
            userRole.setUserId(userId);
            list.add(userRole);
        });
        sysUserRoleService.remove(
                new LambdaQueryWrapper<SysUserRole>()
                        .eq(SysUserRole::getUserId, userId)
        );
        sysUserRoleService.saveBatch(list);
        //删除缓存
        sysUserService.clearUserAuthorityInfo(sysUserService.getById(userId).getUsername());
        return Result.succ("");
    }

    /**
     * 重置密码
     */
    @PostMapping("/repass")
    @PreAuthorize("hasAuthority('sys:user:repass')")
    public Result repass(@RequestBody Long userId) {
        SysUser user = sysUserService.getById(userId);
        user.setPassword(Const.DEFULT_PASSWORD);
        user.setUpdated(LocalDateTime.now());
        sysUserService.updateById(user);
        return Result.succ("");
    }

    /**
     * 修改密码
     */
    @PostMapping("/updatePass")
    public Result updatePass(@Validated @RequestBody PassDto passDto, Principal principal) {
        SysUser user = sysUserService.getByUserName(principal.getName());
        boolean matches = passwordEncoder.matches(passDto.getCurrentpass(), user.getPassword());
        if (!matches) {
            return Result.fail("旧密码不正确!");
        }
        user.setPassword(passwordEncoder.encode(passDto.getPassword()));
        user.setUpdated(LocalDateTime.now());
        sysUserService.updateById(user);
        return Result.succ("");
    }
}
